<template>
<div id="userEdit">
    <div id="userEdit-header">
        <div id="leftBox">
            <el-button icon="el-icon-circle-plus-outline" type="primary" size="small" @click="initFromData(); fromModel = 'add'; dialogVisible = true">新增用户</el-button>
            <el-button icon="el-icon-arrow-left" type="primary" size="small" v-if="searchMode" @click="searchMode = false">退出搜索模式</el-button>
        </div>
        <el-input placeholder="请输入内容" v-model="searchContent" class="input-with-select" @keyup.enter.native="searchUserInfo()" style="width: 520px;">
            <el-select slot="prepend" placeholder="请选择" v-model="searchKeyword" style="width: 100px; font-size: 12px;">
                <el-option label="姓名" value="name"></el-option>
                <el-option label="地址" value="address"></el-option>
                <el-option label="邮箱" value="email"></el-option>
                <el-option label="手机号码" value="phone"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="searchUserInfo()"></el-button>
        </el-input>
    </div>
    <div id="tableBox">
        <el-table
        :data="userData"
        style="width: calc(100% - 40px); margin: 0 auto;"
        height="100%">
            <el-table-column
            fixed="left"
            prop="name"
            label="姓名"
            width="100">
            </el-table-column>
            <el-table-column
            prop="sex"
            label="性别"
            width="60">
            </el-table-column>
            <el-table-column
            prop="address"
            label="地址"
            width="340">
            </el-table-column>
            <el-table-column
            prop="email"
            label="邮箱"
            width="260">
            </el-table-column>
            <el-table-column
            prop="phone"
            label="手机号码"
            width="120">
            </el-table-column>
            <el-table-column
            prop="createTime"
            label="上次登陆时间"
            width="160">
            </el-table-column>
            <el-table-column
            fixed="right"
            label="操作"
            min-width="142">
            <template slot-scope="scope">
                <el-button
                size="mini"
                @click="fromModel = 'edit'; userInfoEdit(scope.row)">编辑</el-button>
                <el-button
                size="mini"
                type="danger"
                @click="delUserInfo(scope.row.id)">删除</el-button>
            </template>
            </el-table-column>
        </el-table>
    </div>
    <div id="paginationBox">
        <div>
            每页数量
            <el-select v-model="pageSize" style="width: 70px;" size="small">
                <el-option
                v-for="(item, index) in 41"
                :key="item"
                :label="index+10"
                :value="index+10">
                </el-option>
            </el-select>
            &nbsp;&nbsp;&nbsp;
            共 {{ total }} 条数据
        </div>
        <el-pagination
            layout="prev, pager, next"
            :background="true"
            :page-size="pageSize"
            :total="total"
            @current-change="currentChange">
        </el-pagination>
    </div>

    <el-dialog
    :title="fromModel === 'add' ? '添加用户信息' : '编辑用户信息'"
    :visible.sync="dialogVisible"
    @close="fromClose()"
    width="520px">
        <el-form ref="form" :model="fromData" :rules="fromRules" label-width="80px" style="width: calc(100% - 20px)">
            <el-form-item label="姓名" prop="name">
                <el-input v-model="fromData.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-select v-model="fromData.sex" placeholder="请选择性别">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="地址" prop="address">
                <el-input v-model="fromData.address" placeholder="请输入地址"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="fromData.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
                <el-input v-model="fromData.phone" placeholder="请输入手机号码"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="fromConfirm()">确 定</el-button>
        </span>
    </el-dialog>
</div>
</template>

<script>
import { userData, addUserInfo, editUserInfo, deltUserInfo, searchUserInfo } from '@/api/userApi'
export default {
    name:'userEdit',
    data(){
        return {
            dialogVisible:false, // 用户数据编辑对话框是否展示
            userData: [], // 请求的用户数据
            total:null, // 用户数据总条数
            pageSize:15, // 每页用户数据的条数
            page:1, // 当前页面
            fromData:{}, // 表单数据
            fromModel:'add', // 表单模式
            fromRules: { // 表单验证规则
                name: [
                    { required: true, message: '姓名不能为空', trigger: 'blur' },
                    { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
                ],
                sex: [
                    { required: true, message: '性别是必选的', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '地址不能为空', trigger: 'blur' },
                    { min: 6, max: 32, message: '长度在 6 到 32 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                ],
                phone: [
                    { validator:(rule, value, callback) => {
                        const pattern = /0?(13|14|15|17|18|19)[0-9]{9}/
                        if (value === '') {
                            callback(new Error('手机号码不能为空'));
                        } else if (!pattern.test(value)) {
                            callback(new Error('请输入正确的手机号码'));
                        } else {
                            callback();
                        }
                    }, trigger: 'change' }
                ],
            },
            searchContent:'', // 搜索内容
            searchKeyword:'name', // 搜索关键字
            tempData:null, // 临时数据
            searchMode:false, // 是否处于搜索模式
            tempSearch:null, // 搜索临时数据
        }
    },
    methods:{
        fromClose() { // 表单组件关闭回调
            this.$refs['form'].resetFields()
        },
        userDataFunc(s){ // 用户数据请求函数
            if(s && this.searchMode) return this.searchUserInfo(this.tempSearch)

            userData({
                page: this.page,
                pageSize: this.pageSize
            }).then(res =>{
                this.userData = res.data
                this.total = res.total
            })
        },
        currentChange(s){ // 分页切换函数
            this.page = s
            if(this.searchMode){
                this.tempSearch.page = s
            }
            this.userDataFunc(this.searchMode)
        },
        initFromData(){ // 初始化表单数据函数
            this.fromData = {
                name:'',
                sex:'',
                address:'',
                email:'',
                phone:'',
            }
        },
        fromConfirm(){ // 表单确定按钮点击事件
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if(this.fromModel === 'add'){
                        this.addUSerInfo()
                    }else{
                        this.editUserInfo()
                    }

                    this.dialogVisible = false
                }
            });
        },
        addUSerInfo(){ // 添加用户信息函数
            addUserInfo(this.fromData).then(() =>{
                this.page = 1
                this.userDataFunc(this.searchMode)
                this.$message({
                    message:'添加成功',
                    type:'success'
                });
            })
        },
        userInfoEdit(data){ // 用户信息编辑按钮点击事件
            this.fromData = JSON.parse(JSON.stringify(data))

            this.dialogVisible = true
        },
        editUserInfo(){ // 修改用户信息函数
            editUserInfo(this.fromData).then(() =>{
                this.userDataFunc(this.searchMode)
                this.$message({
                    message:'更改成功',
                    type:'success'
                });
            })
        },
        delUserInfo(id){ // 删除用户信息函数
            this.$confirm('确定删除该用户', '提示', {
            type: 'warning'
            }).then(() => {
                deltUserInfo({id}).then(() =>{
                    this.userDataFunc(this.searchMode)
                    this.$message({
                        type: 'success',
                        message: '删除成功'
                    });
                })
            })
        },
        searchUserInfo(obj){ // 搜索用户信息函数
            const obj2 = obj || {
                key: this.searchKeyword,
                value: this.searchContent,
                pageSize: this.pageSize,
                page: this.page
            }

            searchUserInfo(obj2).then(res =>{
                if(res.data.length > 0){
                    if(!obj) this.tempSearch = JSON.parse(JSON.stringify(obj2))
                    this.searchMode = true

                    setTimeout(() => {
                        this.userData = res.data
                        this.total = res.total
                    }, 200);
                }else{
                    this.$message({
                        message:'没有数据',
                        type:'warning'
                    });
                }
            })
        }
    },
    created(){
        this.userDataFunc()
    },
    watch:{
        searchMode(newval){
            if(newval){
                const obj = {
                    userData: this.userData,
                    pageSize: this.pageSize,
                    page: this.page,
                    total: this.total
                }

                this.tempData = JSON.parse(JSON.stringify(obj))
            }else{
                const obj = JSON.parse(JSON.stringify(this.tempData))

                this.userData = obj.userData
                this.pageSize = obj.pageSize
                this.page = obj.page
                this.total = obj.total
            }
        },
        pageSize(newval){
            if(this.searchMode) this.tempSearch.pageSize = newval
            this.userDataFunc(this.searchMode)
        },
    },
}
</script>

<style scoped>
#userEdit{
    width: 100%;
    height: 100%;
}
#userEdit-header{
    height: 50px;
    padding: 0 20px 10px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
#tableBox{
    height: calc(100% - 120px);
}
#paginationBox{
    height: 60px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #cfd2d9;
    font-size: 14px;
    padding: 0 10px 0 20px;
}
</style>